<template>
    <div class="progress-wrap">
        <div class="outer">
            <div class="inner-wrap" >
                <div class="inner" @click="turnPosition($event)" ref="progressBarBgRef">
                </div>
                <span class="slider slider1" @mousedown.stop="down($event, 'left')" @touchstart.stop="down($event, 'left')" ref="pogressRef1"
                    :style="{ left: left1 * 100 + '%' }">
                    <span class="slider-line"></span>
                    <span class="slider-circle"></span>
                    <span class="slider-text">{{ formatTime(Math.round(left1*props.duration)) }}</span>
                </span>
                <span class="slider slider2" @mousedown.stop="down($event, 'right')" @touchstart.stop="down($event, 'right')" ref="pogressRef2"
                    :style="{ left: left2 * 100 + '%' }">
                    <span class="slider-text">{{ formatTime(Math.round(left2*props.duration)) }}</span>
                    <span class="slider-line"></span>
                    <span class="slider-circle"></span>
                </span>
            </div>
        </div>
    </div>
</template>
  
<script setup>
import { watch, ref, reactive, toRefs, onMounted, onUnmounted } from 'vue'

const props = defineProps({
    duration: {
        type: Number,
        default: 0
    },
});

const emits = defineEmits(['setProgress'])

const state = reactive({
    left1: 0,
    left2: 1,
    dragType: '',
    isDrag: false
});

// watch(() => props.progress, (val) => {
//     if (!state.isDrag) {
//         state.left = val;
//     }
// });

const { left1, left2, dragType, isDrag } = toRefs(state);

let progressBarBgRef = ref(null)
let pogressRef1 = ref(null);
let pogressRef2 = ref(null);

let position = {
    oriOffestLeft: 0, // 移动开始时进度条的点距离进度条的偏移值
    oriX: 0, // 移动开始时的x坐标
    maxLeft: 0, // 向左最大可拖动距离
    maxRight: 0 // 向右最大可拖动距离
};

const formatTime = time => {
	if (isNaN(time) || time < 0) return "00:00"; // 确保时间为有效数字且为正
	const minutes = Math.floor(time / 60);
	const seconds = Math.floor(time % 60);
	return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
};

//点击进度条某个位置播放
const turnPosition = (e) => {
    console.log('e.target',e, e.target);
    if (e.target == pogressRef1.value || e.target == pogressRef2.value) {
        console.log('111111');
        return;
    }
    // console.log('turnPosition',e);
    // // console.log(this.$refs.audio.fastSeek);
    // // console.log("turnPosition", e, e.layerX);
    // // console.log(e.layerX, document.querySelector(".time-line").clientWidth);
    // // console.log(
    //     this.$refs.audio.duration,
    //     (e.layerX / document.querySelector(".time-line").clientWidth) *
    //     this.$refs.audio.duration
    // );
    // this.$refs.audio.currentTime =
    //     (e.layerX / document.querySelector(".time-line").clientWidth) *
    //     this.$refs.audio.duration;

    let pgsWidth = parseFloat(window.getComputedStyle(progressBarBgRef.value, null).width.replace('px', ''));
    let rate = e.offsetX / pgsWidth;

    console.log('e.offsetX / pgsWidth', e.offsetX, pgsWidth);

    if (Math.abs(rate - state.left1) < Math.abs(rate - state.left2)) {
        state.left1 = rate;
    } else {
        state.left2 = rate;
    }

    emits('upDateRepeatTime', Math.min(state.left1, state.left2), Math.max(state.left1, state.left2));


    // emits('setProgress', state.left1);
    // console.log('state.left', state.left);


}

// function updateProgress(audio) {
//     let value = audio.currentTime / audio.duration;
//     document.getElementById('progressBar').style.width = value * 100 + '%';
//     document.getElementById('progressDot').style.left = value * 100 + '%';
// }

onMounted(() => {
});

onUnmounted(() => {
});

function down(event, type) {

    console.log('down',event, type);

    state.dragType = type;
    // console.log('down-myOrientation',window.myOrientation);

    state.isDrag = true;

    if (type == 'left') {
        position.oriOffestLeft = pogressRef1.value.offsetLeft;
    } else {
        position.oriOffestLeft = pogressRef2.value.offsetLeft;
    }

    if (window.myOrientation == 'landscape') {
        position.oriX = event.touches ? event.touches[0].clientX : event.clientX; // 要同时适配mousedown和touchstart事件
    } else {
        position.oriX = event.touches ? event.touches[0].clientY : event.clientY; // 要同时适配mousedown和touchstart事件
    }

    position.maxLeft = position.oriOffestLeft; // 向左最大可拖动距离
    position.maxRight = progressBarBgRef.value.offsetWidth - position.oriOffestLeft; // 向右最大可拖动距离

    // 禁止默认事件（避免鼠标拖拽进度点的时候选中文字）
    if (event && event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }

    // 禁止事件冒泡
    if (event && event.stopPropagation) {
        event.stopPropagation();
    } else {
        window.event.cancelBubble = true;
    }

    // 开始拖动
    document.addEventListener('mousemove', move);
    document.addEventListener('touchmove', move);

    // 拖动结束
    document.addEventListener('mouseup', end);
    document.addEventListener('touchend', end);
}

function move(event) {
    console.log('move',event);
    // console.log('move-myOrientation',window.myOrientation);

    let clientX = 0; // 要同时适配mousemove和touchmove事件

    let touch = event.touches ? event.touches[0] : event;

    // console.log('touch',touch);
    // console.log('value', touch.clientX, touch.clientY);

    if (window.myOrientation == 'landscape') {
        clientX = touch.clientX; // 要同时适配mousedown和touchstart事件
    } else {
        clientX = touch.clientY; // 要同时适配mousedown和touchstart事件
    }

    // console.log('clientX',clientX);
    let length = clientX - position.oriX;
    if (length > position.maxRight) {
        length = position.maxRight;
    } else if (length < -position.maxLeft) {
        length = -position.maxLeft;
    }

    // console.log('length',length);
    let progressBarBg = progressBarBgRef.value;
    let pgsWidth = parseFloat(window.getComputedStyle(progressBarBg, null).width.replace('px', ''));
    let rate = (position.oriOffestLeft + length) / pgsWidth;

    if (state.dragType == 'left') {
        state.left1 = rate;
    } else {
        state.left2 = rate;
    }

    // // console.log('state.left',state.left);

    // audio.currentTime = audio.duration * rate;
    // updateProgress(audio);

}

function end() {
    state.isDrag = false;
    // // console.log('end', state.left);
    // emits('setProgress', state.left1);
    emits('upDateRepeatTime', Math.min(state.left1, state.left2), Math.max(state.left1, state.left2));

    // 开始拖动
    document.removeEventListener('mousemove', move);
    document.removeEventListener('touchmove', move);

    // 拖动结束
    document.removeEventListener('mouseup', end);
    document.removeEventListener('touchend', end);

    position = {
        oriOffestLeft: 0, // 移动开始时进度条的点距离进度条的偏移值
        oriX: 0, // 移动开始时的x坐标
        maxLeft: 0, // 向左最大可拖动距离
        maxRight: 0 // 向右最大可拖动距离
    };
}

</script>
  
<style scoped>
.progress-wrap {
    position: relative;
}

.outer {
    background-color: #F4F4F4;
    border-radius: 10px;
    width: 100%;
    height: 70%;
    /* overflow: hidden; */
    position: absolute;
    left: 0%;
    top: 50%;
    transform: translateY(-50%);
    padding: 0 10px;
    box-sizing: border-box;
}

.inner-wrap {
    height: 50%;
    position: absolute;
    left: 1%;
    right: 1%;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
}

.inner {
    width: 100%;
    height: 100%;
    background-image: url("../../public/assets/repeatbg.png");
    /* background-repeat: repeat-x; */
    background-size: auto 100%;
}

.slider {
    position: absolute;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 70px;
    cursor: pointer;
}
.slider .slider-circle {
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 1000px;
    position: absolute;
    transform: translate(-50%, 0);
    background-color: #FFB530;
}
.slider .slider-line {
    background-color: #FFB530;
    height: 46px;
    width: 3px;
    position: absolute;
    transform: translate(-50%, 0);
    border-radius: 1000px;
}

.slider .slider-text {
    color: #FFB530;
    position: absolute;
    transform: translate(-50%, 0);
    font-size: 16px;
}

.slider1 {
    left: 0%;
    top: 50%;
}

.slider1 .slider-circle {
    left: 50%;
    top: 0;
}

.slider1 .slider-line {
    left: 50%;
    top: 10px;
}

.slider1 .slider-text {
    left: 50%;
    bottom: -4px;
}

.slider2 {
    left: 0%;
    top: 50%;
}

.slider2 .slider-circle {
    left: 50%;
    bottom: 0;
}

.slider2 .slider-line {
    left: 50%;
    bottom: 10px;
}

.slider2 .slider-text {
    left: 50%;
    top: -6px;
}

</style>
  